from django.shortcuts import render, HttpResponse, redirect

# Create your views here.
def index(request):
    return HttpResponse("欢迎使用")

def user_add(request):
    return render(request, 'user_add.html')

def user_list(request):
    return render(request, 'user_list.html')

def tpl(request):
    name = "丁佑强"
    roles = ["管理员", "CEO", "保安"]
    n3 = {"name": "dingyouqaing", "age": 26, "salary": 13000}
    n4 = [
        {"name": "丁佑强", "age": 24, "salary": 3000},
        {"name": "林伟", "age": 25, "salary": 4000},
        {"name": "黄菊", "age": 26, "salary": 5000},
    ]
    return render(request, 'tpl.html', {"name": name, "n2": roles, "n3": n3, "n4": n4})

def something(request):
    print(request.method)
    print(request.GET)
    return redirect("http://www.baidu.com")

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('user')
        password = request.POST.get('password')
        if username == 'root' and password == '123456':
            return HttpResponse('登录成功')
        else:
            return render(request, 'login.html', {'error_msg': '登录失败'})

from app01.models import Department, UserInfo
def orm(request):

    # 测试 ORM 操作表中的数据
    # 新增数据
    Department.objects.create(title="销售部")
    Department.objects.create(title="IT部")
    Department.objects.create(title="运营部")
    UserInfo.objects.create(name="丁佑强", password="123", age=19)
    UserInfo.objects.create(name="林伟", password="444", age=29)
    # UserInfo.objects.create(name="黄菊", password="444")  # age不能为空，字段默认是 not null
    # 删除数据
    UserInfo.objects.filter(id=3).delete()  # where id=3 的数据删除
    # UserInfo.objects.all().delete()     # 将整张表数据删除
    # 获取数据
    data_list = UserInfo.objects.all()  # 获取表中所有的数据，获得querySey的数据列表
    data_list2 = UserInfo.objects.filter(id=1)  # where id=1，但同样是querySet
    data_list3 = UserInfo.objects.filter(id=23).first()  # where id=23 ，然后取得列表中的对象
    print(data_list)
    for obj in data_list:
        print(obj.id, obj.name, obj.password, obj.age, obj.size)
    print(data_list3)
    # 更新数据
    UserInfo.objects.all().update(password="999")  # 全表的password字段都改为999
    UserInfo.objects.filter(id=23).update(password="888")  # 筛选条件
    return HttpResponse("成功")

def info_list(request):
    # 1. 获取数据库中用户的信息
    data_list = UserInfo.objects.all()
    print(data_list)

    return render(request, "info_list.html", {"data_list": data_list})

def info_add(request):
    if request.method == 'GET':
        return render(request, 'info_add.html')
    username = request.POST.get("user")
    password = request.POST.get("password")
    age = request.POST.get("age")
    UserInfo.objects.create(name=username, password=password, age=age)
    return redirect("/info/list/")

def info_delete(request):
    nid = request.GET.get('nid')
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/info/list/")